#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int a[N];
int ac[N];
int fa[N];
int siz[N];
int siz1[N];
int gf(int x){
    if(fa[x] == x){
        return x;
    }
    return fa[x] = gf(fa[x]);
}
void merge(int x,int y){
    int xx = gf(x),yy = gf(y);
    if(xx == yy)return;
    siz[xx] += siz[yy];
    siz[yy] = 0;
    siz1[xx] += siz1[yy];
    siz1[yy] = 0;
    fa[yy] = xx;
}
vector<int> mp[N];
int n;
int cnt = 0;
int find(int x,int lmt,int from){
    cnt++;
    if(cnt > n){
        return 0;
    }
    if(a[x] > lmt){
        return 1;
    }
    int res = 0;
    if(a[x] == lmt){
        res++;
    }
    if(x % n + 1 != from){
        res += find(x % n + 1,lmt,x);
    }
    if((x == 1?n:x - 1) != from){
        res += find(x == 1?n:x - 1,lmt,x);
    }
    return res;
}
void solve(){
    cin>>n;
    for(int i = 1;i<=n;i++){
        cin>>a[i];
        fa[i] = i;
        siz[i] =1;
        siz1[i] = 1;
        ac[i] = a[i];
    }
    sort(ac + 1,ac + 1 + n);
    int tot = unique(ac + 1,ac + 1 + n) - ac - 1;
    for(int i = 1;i<=n;i++){
        a[i] = lower_bound(ac + 1,ac + 1 + tot,a[i]) - ac;
    }
    for(int i = 1;i<=tot;i++){
        mp[i].clear();
    }
    for(int i = 1;i<=n;i++){
        mp[a[i]].push_back(i);
    }
    long long ans = 0;
    for(int i = 1;i<=tot;i++){
        long long ansb = ans;
        for(int v: mp[i])
        {
            cnt = 0;
            ans += find(v,i);
        }
        cerr<<ans - ansb<<'\n';
    }
    cout<<ans<<'\n';
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    freopen("forever.in","r",stdin);
    freopen("forever.out","w",stdout);
    int T;
    cin>>T;
    while(T--){
        solve();
    }
}